package com.ivr.cm.service.impl;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import com.ivr.cm.cache.Cacheable;
import com.ivr.cm.data.BaseData;
import com.ivr.cm.service.BaseServiceIF;

/**
 * 添加省市业务逻辑,用户拨打后补充用户的省市信息以便后期使用
 * @author liugeng
 * @date 2015-12-15
 */
public class AddAreaServiceImpl implements BaseServiceIF<BaseData> {
	private static Logger logger = Logger.getLogger(AddAreaServiceImpl.class);
	
	private Cacheable cacheable;

	@SuppressWarnings("unchecked")
	@Override
	public int doProcess(BaseData baseData) {
		ConcurrentHashMap<Integer, String[][]> mobileAreaMap = (ConcurrentHashMap<Integer, String[][]>) cacheable.getCache();
		/**获得被叫长号码*/
		String long_called = baseData.getLong_called();
		/**获得主叫号码*/
		String calling = baseData.getCalling();//主叫号码
		
		String province = "未知";
		String city = "未知";
		
		/**对主叫号码进行号段处理  截取后11位  防止手机号码前面带+86之类*/
		if(calling.length() > 11){
			calling = calling.substring(calling.length() - 11, calling.length());
		}
		
		/**根据主叫号码前7位获得主叫号码的省份  未获得的为未知省份*/
		if(calling.length() > 7){
			String start = calling.substring(0,7);
			Integer startP3 = 0;
			Integer startL4 = 0;
			try{
				startP3 = Integer.parseInt(start.substring(0,3));
				startL4 = Integer.parseInt(start.substring(3,7));
			}catch (NumberFormatException e) {
				logger.error(String.format("[%s][%s][加入省市]数据转化异常:%s", calling,long_called,ExceptionUtils.getFullStackTrace(e)));
				baseData.setProvince(province); 
				baseData.setCity(city);
				return 0;
			}
			
			/**从号段缓存中根据手机号前三位获得后续数组*/
			String temp[][] = mobileAreaMap.get(startP3);
			if(temp == null){
				baseData.setProvince(province); 
				baseData.setCity(city);
				logger.info(String.format("[%s][%s][加入省市]为空,[%s,%s]", calling,long_called,province,city));
				return 0;
			}
			
			/**根据手机号码后四位获得区域信息  0 省份  1 市*/
			String area[] = temp[startL4];
			if(area != null && area.length > 0){
				if(area[0] != null && area[1] != null){
					province = area[0];
					city = area[1];
				}
			}
		}
		
		/**拼装用户的区域信息到基本数据VO*/
		baseData.setProvince(province);
		baseData.setCity(city);
		
		logger.info(String.format("[%s][%s][加入省市][%s,%s]", long_called,calling,province,city));
		/**返回0代表正常状态*/
		return 0;
	}
	
	public Cacheable getCacheable() {
		return cacheable;
	}
	public void setCacheable(Cacheable cacheable) {
		this.cacheable = cacheable;
	}
}